package com.hmall.cart.listener;

import com.hmall.cart.service.ICartService;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConditionalOnClass(RabbitTemplate.class)
public class OrderStatusListener {
    @Autowired
    private ICartService  cartService;
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(value = "order-queue",durable = "true"),
//            exchange = @Exchange(value = "order-exchange",type = ExchangeTypes.TOPIC),
//            key = "order.delete"
//    ))
//    public void handleOrderStatus(Map<String,Object>  cartMap) {
//        List<Long> itemIds = (List<Long>) cartMap.get("itemIds");
//        Integer userId = (Integer) cartMap.get("userId");
//        //Integer 转化为 Long
//       Long userIdss =Long.valueOf( String.valueOf(userId));
//        UserContext.setUser(userIdss);
//        cartService.removeByItemIds(itemIds);
//    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "order-queue",durable = "true"),
            exchange = @Exchange(value = "order-exchange",type = ExchangeTypes.TOPIC),
            key = "order.delete"
    ))
    public void handleOrderStatus(List<Long> itemIds, @Header("userId") Long userId) {
        UserContext.setUser(userId);
        cartService.removeByItemIds(itemIds);
        UserContext.removeUser();
    }
}
